package com.taskinception.utils;

import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.taskinception.R;
import com.taskinception.model.Task;

import java.util.List;

public class TaskListAdapter extends ArrayAdapter<Task> {

    private int resourceId;
    private LayoutInflater inflater;
    private Context ctx;

    public TaskListAdapter(Context context, int textViewResourceId,
	    List<Task> objects) {
	super(context, textViewResourceId, objects);
	inflater = LayoutInflater.from(context);
	resourceId = textViewResourceId;
	ctx = context;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
	final Task task = getItem(position);
	TaskListCache cache;

	// Determine the source of the view. Get from cache if available.
	// Inflate it otherwise
	if (convertView == null) {
	    convertView = (LinearLayout) inflater.inflate(resourceId, null);
	    cache = new TaskListCache(convertView);
	    convertView.setTag(cache);
	} else {
	    convertView = (LinearLayout) convertView;
	    cache = (TaskListCache) convertView.getTag();
	}

	// Make the id of the current task available for the click actions
	convertView.setTag(R.id.task_id, task.getId());

	ImageView img = (ImageView) convertView
		.findViewById(R.id.task_share_image);
	if (task.isShared()) {
	    // TODO: Instead of setting a color overlay, add a drawable to the
	    // resources with the right color
	    img.setColorFilter(Color.parseColor("#008000"),
		    PorterDuff.Mode.SRC_IN);
	}
	// img.setOnClickListener(new OnClickListener() {
	//
	// @Override
	// public void onClick(View v) {
	// Intent intent = new Intent(ctx, WiFiDirectActivity.class);
	// intent.putExtra(WiFiDirectActivity.TASK_ID, task.getId());
	// intent.putExtra(WiFiDirectActivity.MODE, "share");
	// ctx.startActivity(intent);
	// }
	// });

	TextView title = (TextView) convertView.findViewById(R.id.task_title);
	title.setText(task.getTitle());

	CheckBox check = (CheckBox) convertView.findViewById(R.id.task_checked);
	check.setChecked(task.isDone());

	TextView progress = (TextView) convertView
		.findViewById(R.id.task_progress);

	if (task.isList()) {
	    progress.setText(task.getProgress());
	    check.setClickable(false);
	} else {
	    progress.setVisibility(View.GONE);
	    check.setClickable(true);
	}

	return convertView;
    }
}
